<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>欢迎使用学生信息管理系统</h1>
      <p>当前用户：{{ userInfo.hm }} | 角色：{{ getRoleName(userInfo.role) }}</p>
    </div>
    
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon student">
              <el-icon><User /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.studentCount }}</h3>
              <p>学生总数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon course">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.courseCount }}</h3>
              <p>课程总数</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon enrollment">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.enrollmentCount }}</h3>
              <p>选课记录</p>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon average">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stats-info">
              <h3>{{ stats.averageScore }}</h3>
              <p>平均成绩</p>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 快捷操作 -->
    <el-row :gutter="20" class="quick-actions">
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>快捷操作</span>
          </template>
          <div class="action-buttons">
            <el-button type="primary" @click="$router.push('/students')">
              <el-icon><User /></el-icon>
              学生管理
            </el-button>
            <el-button type="success" @click="$router.push('/courses')">
              <el-icon><Reading /></el-icon>
              课程管理
            </el-button>
            <el-button type="warning" @click="$router.push('/enrollments')">
              <el-icon><Document /></el-icon>
              选课管理
            </el-button>
            <el-button type="info" @click="$router.push('/users')" v-if="userInfo.role === 0">
              <el-icon><UserFilled /></el-icon>
              用户管理
            </el-button>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>系统信息</span>
          </template>
          <div class="system-info">
            <p><strong>系统版本：</strong>v1.0.0</p>
            <p><strong>最后登录：</strong>{{ formatDate(new Date()) }}</p>
            <p><strong>在线时长：</strong>{{ onlineTime }}</p>
            <p><strong>系统状态：</strong><el-tag type="success">正常运行</el-tag></p>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { User, Reading, Document, UserFilled, TrendCharts } from '@element-plus/icons-vue'
import { studentApi, courseApi, enrollmentApi } from '@/api/index'

export default {
  name: 'Dashboard',
  components: {
    User,
    Reading,
    Document,
    UserFilled,
    TrendCharts
  },
  setup() {
    const userInfo = computed(() => {
      return JSON.parse(localStorage.getItem('userInfo') || '{}')
    })
    
    const stats = reactive({
      studentCount: 0,
      courseCount: 0,
      enrollmentCount: 0,
      averageScore: '0.0'
    })
    
    const onlineTime = ref('00:00:00')
    const startTime = Date.now()
    
    const getRoleName = (role) => {
      const roleMap = {
        0: '管理员',
        1: '教师',
        2: '学生'
      }
      return roleMap[role] || '未知'
    }
    
    const formatDate = (date) => {
      return date.toLocaleString('zh-CN')
    }
    
    const updateOnlineTime = () => {
      const now = Date.now()
      const diff = now - startTime
      const hours = Math.floor(diff / (1000 * 60 * 60))
      const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diff % (1000 * 60)) / 1000)
      onlineTime.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
    }
    
    const loadStats = async () => {
      try {
        // 获取学生总数
        const studentsRes = await studentApi.getAllStudents()
        if (studentsRes.code === 200) {
          stats.studentCount = studentsRes.data.length
        }
        
        // 获取课程总数
        const coursesRes = await courseApi.getAllCourses()
        if (coursesRes.code === 200) {
          stats.courseCount = coursesRes.data.length
        }
        
        // 获取选课记录总数
        const enrollmentsRes = await enrollmentApi.getAllEnrollments()
        if (enrollmentsRes.code === 200) {
          stats.enrollmentCount = enrollmentsRes.data.length
        }
        
        // 获取平均成绩
        const avgRes = await courseApi.getAllCoursesAverage()
        if (avgRes.code === 200) {
          stats.averageScore = avgRes.data.toFixed(1)
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    }
    
    onMounted(() => {
      loadStats()
      // 每秒更新在线时长
      setInterval(updateOnlineTime, 1000)
    })
    
    return {
      userInfo,
      stats,
      onlineTime,
      getRoleName,
      formatDate
    }
  }
}
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.dashboard-header {
  margin-bottom: 30px;
  text-align: center;
}

.dashboard-header h1 {
  color: #333;
  margin-bottom: 10px;
}

.dashboard-header p {
  color: #666;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 30px;
}

.stats-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  font-size: 24px;
  color: white;
}

.stats-icon.student {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stats-icon.course {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stats-icon.enrollment {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stats-icon.average {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stats-info h3 {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin: 0 0 5px 0;
}

.stats-info p {
  color: #666;
  margin: 0;
  font-size: 14px;
}

.quick-actions {
  margin-bottom: 30px;
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.action-buttons .el-button {
  flex: 1;
  min-width: 120px;
}

.system-info p {
  margin: 10px 0;
  color: #666;
}

.system-info strong {
  color: #333;
}
</style>